	export default {
		name: "readxlsx",
        props: {
		    tbyoptions: {type: Array, required: true},
        },
		setup(props, {emit}) {
		    const { smartSpeak } = inject('speech'); //语音
			const tempjson = ref([]);
			const pageState = ref({total: 0,percent: 0});
			const fieldsConfig = ref({});
			const upload = ref(null);
			const formRef = ref();
			const at = ref();
			const newbgsx = ref({ formname: '', fields: {}, dblcxx: [], cxtj: [], kfcx: [] })
            const rules = reactive({
                formname: [{required: true, message: '请输入查询名称'},{min: 2,max: 200,message: '查询名称字数限制在2和200之间'}],
                kfcx: [{required: true,message: '请选择开放查询的列'}],
                fields: [{required: true,message: '请设置字段'},
                	{
                		validator: (rule, value, callback) => {
                        const temp = value || {};
                        if (Object.keys(temp).length === 0) {
                        	callback(new Error('至少需要设置一个字段'));
                        	return;
                        }
                        for (const [fieldKey, config] of Object.entries(temp)) {
                        	// 字段名称校验
                        	if (!config.name?.trim()) {
                        		callback(new Error(`${fieldKey} 字段名称不得为空`));
                        		return;
                        	}
                        	// multiimage 类型校验
                        	if (config.type === 'multiimage' && !config.max) {
                        		callback(new Error(`${config.name} 数量限制不得为空`));
                        		return;
                        	}
                        	// 选项类型校验
                        	if (['select', 'muselect', 'radio', 'checkbox'].includes(config.type) && !config.options) {
                        		callback(new Error(`${config.name} 选项不得为空`));
                        		return;
                        	}
                        	// 查询条件冲突校验
                        	if (['image', 'multiimage', 'textarea', 'muselect', 'checkbox', 'subtable'].includes(config.type) && newbgsx.value.cxtj?.includes(fieldKey)
                        	) {
                        		callback(new Error(`${config.name} 图片、多选、多行文本和子表不能作为查询条件`));
                        		return;
                        	}
                        }
                        callback();
                		}
                	}
                ]
            });
            const activeName = ref('first'); // 默认tab
            const fieldOrder = ref([]); // 维护字段顺序
            const aiPrompt = ref('');
            const isGenerating = ref(false);
            const pollId = ref(null); // 修改为null初始化
            // 导入配置对话框相关状态
            const showImportDialog = ref(false);
            const importConfigs = ref([]);
            const selectedConfigIndex = ref(0);
            let importResolve = null
            
            const zdoption = computed(() => { // 计算字段选项
                return Object.entries(newbgsx.value.fields).map(([value, field]) => ({
                    label: field.name,
                    value: value
                }));
            });
            
            //重置数据
			const resetUploadState = () => {
				pageState.value.percent = 0;
				pageState.value.total = 0;
				tempjson.value = [];
			};
			
			const handleFileChange = async (file) => {
				try {
					resetUploadState();
					const validFile = getValidFile(file);
					const jsonData = await readExcelFile(validFile);
					console.log('数据处理完成')
					await processImportedData(jsonData);
					newbgsx.value.fields = fieldsConfig.value;
					fieldOrder.value = Object.keys(fieldsConfig.value);
					newbgsx.value.kfcx = Object.keys(newbgsx.value.fields);
					newbgsx.value.cxtj = [];
				} catch (error) {
					console.error(' 文件处理失败:', error);
    				ElMessage.error(error.message);
				}
			};

			const processImportedData = (jsonData) => {
				if (!jsonData?.length) throw new Error('表格数据为空');
				fieldsConfig.value = {};
				const sampleRow = jsonData[0];
				Object.keys(sampleRow).forEach((key, index) => {
					const fieldKey = `K${index + 1}`;
					const sampleValue = sampleRow[key];
					// 类型检测，自动判断是否图片
                    let fieldType = "text";
                    let placeholder = `请输入${key}`;
                    if (typeof sampleValue === 'string') {
                        if (window.validators.isImageUrl(sampleValue)) {
                            fieldType = "image";
                            placeholder = `请上传${key}`
                        }
                    }
                    fieldsConfig.value[fieldKey] = {
						type: fieldType,
						name: key,
						placeholder: placeholder,
						required: false
					};
				});
				tempjson.value = jsonData.filter(row =>
					Object.values(row).some(v => v !== null && v !== undefined && v !== '')
				);
				pageState.value.total = tempjson.value.length;
			};

            const beforeUpload = (file) => {
                const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                const isXlsx = file.name.endsWith('.xlsx');
                if (!isExcel || !isXlsx) {
                    ElMessage.error('只能上传.xlsx格式的Excel文件!');
                    return false;
                }
                return true;
            };
			
            // 创建项目
            const handleCreate = _.debounce(async() => {
                try {
                    const valid = await formRef.value.validate();
                    if (!valid) return;
                    const res = await addbgsxapi(newbgsx.value);
                    if (res.tablename) {
                        if(activeName.value == 'first') {
                            await insertdata(res.tablename);
                            ElMessage.success("创建成功，开始导入");
                        }else{
                            ElMessage.success("创建成功");
                            setTimeout(() => {
                    			closeDialog();
                    			emit('update-success'); // 触发父组件更新
                    		}, 500);
                        }
                    }
                } catch (error) {
                    console.error('表单验证失败:', error);
                    ElMessage.error('表单验证失败，请检查输入');
                    smartSpeak('表单验证失败');
                }
            }, 300);
    
            // 数据导入
            const insertdata = async (tableName) => {
                const BATCH_SIZE = 600
                let currentBatch = []
                let processedCount = 0
                for (const item of tempjson.value) {
                    processedCount++
                    currentBatch.push(processDataItem(item))
                    if (currentBatch.length >= BATCH_SIZE) {
                        await sendBatchData(tableName, currentBatch)
                        currentBatch = []
                    }
                    updateProgress(processedCount)
                }
                if (currentBatch.length > 0) {
                    await sendBatchData(tableName, currentBatch)
                }
                ElMessage.success('数据导入完成');
                smartSpeak('数据导入完成');
                setTimeout(() => {
        			closeDialog();
        			emit('update-success'); // 触发父组件更新
        		}, 500);
            }
    
			const processDataItem = (rawItem) => {
				return Object.entries(newbgsx.value.fields).reduce((item, [fieldKey, config]) => {
					item[fieldKey] = String(rawItem[config.name] || '');
					return item;
				}, {});
			}
    
            const updateProgress = (processed) => {
                pageState.value.percent = Math.min(99, Math.floor((processed / pageState.value.total) * 100));
            }
    
            const sendBatchData = async (tableName, data) => {
                await tablepost({ tablename: tableName, data });
            }
            
            //关闭弹窗
			const closeDialog = () => {
			    //upload.value.clearFiles();//清空文件选择器
			    resetUploadState();
                emit('update:dialog-visible', false); // 通知父组件更新状态
            };
            
            // 添加字段
            const addField = () => {
                const generateFieldKey = () => {
                    const keys = Object.keys(newbgsx.value.fields);
                    const maxIndex = keys.reduce((max, k) => {
                        const num = parseInt(k.replace('K', ''));
                        return num > max ? num : max;
                    }, -1);
                    return `K${maxIndex + 1}`;
                };
                const newKey = generateFieldKey();
                newbgsx.value.fields[newKey] = {
                    type: "text",
                    placeholder: "请输入列名",
                    required: false,
                    name: ''
                };
                fieldOrder.value.push(newKey);
                newbgsx.value.kfcx = Object.keys(newbgsx.value.fields);
            };
    
            // 删除字段
            const removeField = (key) => {
                delete newbgsx.value.fields[key];
                fieldOrder.value = fieldOrder.value.filter(k => k !== key);
                newbgsx.value.kfcx = Object.keys(newbgsx.value.fields);
            };
    
            // 移动字段顺序
            const moveItemUp = (key) => {
                const index = fieldOrder.value.indexOf(key);
                if (index > 0) {
                    const newOrder = [...fieldOrder.value];
                    [newOrder[index], newOrder[index - 1]] = [newOrder[index - 1], newOrder[index]];
                    fieldOrder.value = newOrder;
                }
            };
    
            const moveItemDown = (key) => {
                const index = fieldOrder.value.indexOf(key);
                if (index < fieldOrder.value.length - 1) {
                    const newOrder = [...fieldOrder.value];
                    [newOrder[index], newOrder[index + 1]] = [newOrder[index + 1], newOrder[index]];
                    fieldOrder.value = newOrder;
                }
            };
            
			// AI生成表单方法
			const generateAIForm = async () => {
				if (!aiPrompt.value.trim()) {
					ElMessage.warning('请输入表单需求描述');
					return;
				}
				try {
					isGenerating.value = true;
					const structuredPrompt = `
                    请根据以下需求生成2-60个表单字段名称，直接返回JSON数组格式：
                    示例：["姓名", "年龄", "头像上传"]
                    
                    要求：
                    1. 只返回字段名称数组
                    2. 使用中文命名
                    3. 避免特殊符号
                    4. 字段总数在2到60个之间
                    
                    需求：${aiPrompt.value}`;
					const result = await blogformai({prompt: structuredPrompt});
					if (!result.taskId) {
						throw new Error('生成任务创建失败');
					}
					startLongPolling(result.taskId);
				} catch (error) {
					ElMessage.error('表单生成失败: ' + error.message);
				} finally {
				    setTimeout(() => {
            			isGenerating.value = false;
            		}, 10000);
				}
			};

			// 长轮询处理
            const startLongPolling = (taskId) => {
                pollId.value = setInterval(async () => {
                    try {
                        const res = await blogformai({ prompt: aiPrompt.value, pollId: taskId });
                        if (res.completed) {
                            stopLongPolling();
                            if (!res.result) throw new Error('回复为空，请重试');
                            // 执行修复
                            const fixedString = fixJsonFormat(res.result);
                            console.log('修复后的JSON:', fixedString);
                            // 解析数据
                            let aiData;
                            try {
                                aiData = JSON.parse(fixedString);
                            } catch (e) {
                                throw new Error('响应数据不是有效的JSON格式: ' + e.message);
                            }
                            // 数据校验
                            const { error, value } = validateStructure(aiData);
                            if (error) {
                                console.error('校验失败详情:', error);
                                throw new Error(`数据结构校验失败: ${error.message}`);
                            }
                            // 生成完整配置
                            const fullConfig = autoGenerateConfig(value);
                            // 更新表单配置（修复属性大小写问题）
                            newbgsx.value.fields = fullConfig.reduce((acc, field) => {
                                acc[field.key] = {
        							type: field.type || getAutoType(field.name),
        							name: field.name,
        							placeholder: getPlaceholder(field),
        							required: field.required,
        							help: getHelpText(field),
        							sfzoptions: {name: '',sex: '',mz: '',day: '',ade: '',old: ''},
        							zboptions: [],
        							options: field.options || '选项1/选项2/选项3',
        							max: 9 // 默认多图上传最大数量
                                };
                                return acc;
                            }, {});
                            newbgsx.value.formname = aiPrompt.value;
                            fieldOrder.value = fullConfig.map(f => f.key); 
                            newbgsx.value.kfcx = Object.keys(newbgsx.value.fields);
                            console.log('生成配置:', newbgsx.value.fields);
                            ElMessage.success(`成功生成${fullConfig.length}个字段`);
                            activeName.value = 'two';
                            isGenerating.value = false;
                        }
                    } catch (error) {
                        stopLongPolling();
                        ElMessage.error(`处理失败: ${error.message}`);
                        console.error('完整错误日志:', error);
                    }
                }, 1500);
            };

			const stopLongPolling = () => {
				clearInterval(pollId.value);
				pollId.value = null;
			}
            
            //字段类型变化时，如果是身份证识别要检查sfzoptions
            const lxchang = (e) => {
            	let k = at.value;
            	if (e == 'idcard' && typeof newbgsx.value.fields[k].sfzoptions === 'undefined') {
            		newbgsx.value.fields[k].sfzoptions = {name: '',sex: '',mz: '',day: '',ade: '',old: ''};
            	}
            	if(e == 'subtable' && !Array.isArray(newbgsx.value.fields[k].zboptions)) {
            		newbgsx.value.fields[k].zboptions = [];
            	}
            };
            
            //导入json配置
            const handleJsonImport = async (file) => {
                try {
                    // 读取文件内容
                    const reader = new FileReader();
                    const jsonContent = await new Promise((resolve, reject) => {
                        reader.onload = e => resolve(e.target.result);
                        reader.onerror = reject;
                        reader.readAsText(file.raw);
                    });
                    // 解析并统一为数组格式
                    let importedData = JSON.parse(jsonContent);
                    if (!Array.isArray(importedData)) {
                        importedData = [importedData];
                    }
                    // 深度校验配置结构
                    const validConfigs = importedData.filter(config => {
                        const hasBasicProps = config.formname && config.fields;
                        const fieldsValid = Object.values(config.fields).every(field => ['type', 'name', 'placeholder'].every(k => field.hasOwnProperty(k)));
                        return hasBasicProps && fieldsValid;
                    });
                    if (validConfigs.length === 0) {
                        throw new Error('未找到有效配置项');
                    }
                    // 处理配置选择
                    const selectedConfig = validConfigs.length === 1 ? validConfigs[0] : await showConfigSelection(validConfigs);
                    // 更新组件状态
                    updateComponentState(selectedConfig);
                    ElMessage.success('配置导入成功');
                    smartSpeak('配置导入完成');
                } catch (error) {
                    handleImportError(error);
                }
            };
                
            // 显示配置选择对话框
            const showConfigSelection = (configs) => {
                return new Promise((resolve, reject) => {
                    importConfigs.value = configs;
                    selectedConfigIndex.value = 0;
                    showImportDialog.value = true;
                    importResolve = resolve;
                });
            };
            
            // 确认导入选择
            const confirmImport = () => {
                showImportDialog.value = false;
                const selected = importConfigs.value[selectedConfigIndex.value];
                importResolve(selected);
            };
            
            // 状态更新函数
            const updateComponentState = (config) => {
                const {CreatedAt, CreatedBy, UpdatedAt, id, tablename, ...bgsx} = config;
                newbgsx.value = {
                    ...bgsx,
                    formname: config.formname,
                    fields: config.fields,
                    dblcxx: config.dblcxx || [],
                    cxtj: config.cxtj || [],
                    kfcx: config.kfcx || Object.keys(config.fields)
                };
                fieldOrder.value = Object.keys(config.fields);
                activeName.value = 'two';
            };
            
            // 错误处理函数
            const handleImportError = (error) => {
                console.error('配置导入失败:', error);
                const message = error.message.includes('JSON') ? '文件格式错误，请检查是否为合法JSON' : error.message;
                ElMessage.error(`导入失败: ${message}`);
                smartSpeak('导入失败，请检查文件格式');
            };

			return {
			    zdoption,
			    lxchang,
			    at,
			    lx,
			    pollId,
			    startLongPolling,
			    stopLongPolling,
                aiPrompt,
                isGenerating,
                generateAIForm,
			    activeName,
			    addField,
			    removeField,
			    moveItemUp,
			    moveItemDown,
			    fieldOrder,
				tempjson,
				pageState,
				fieldsConfig,
				upload,
				handleFileChange,
				readExcelFile,
				readImages,
				processFile,
				extractRelativePath,
				extractIDFromFormula,
				isSpecialEmpty,
				processImportedData,
				beforeUpload,
				newbgsx,
				formRef,
                rules,
                handleCreate,
                getcolumns,
                gettempdata,
                closeDialog,
                handleJsonImport, showImportDialog, importConfigs, selectedConfigIndex, importResolve, confirmImport, 
                examplePrompts: [
                    {
                        label: '员工信息表',
                        text: '创建员工信息登记表，需要包含以下字段：姓名、性别、身份证号、入职日期、部门、职位、联系电话、邮箱、紧急联系人、学历、工作经历、证件照'
                    },
                    {
                        label: '活动报名表',
                        text: '生成活动报名表单，要求包含：姓名、手机号、参加人数、报名项目（单选）、饮食禁忌（多选）、身份证号、上传健康码截图'
                    },
                    {
                        label: '问卷调查表', 
                        text: '创建满意度调查表，包含：调查日期、客户姓名、联系方式、满意度评分（1-5分）、改进建议（多行文本）、是否愿意推荐（单选）'
                    },
                    {
                        label: '商品订单表',
                        text: '生成商品订购表单，需要：商品选择（多选）、数量、收货人姓名、联系电话、详细地址、支付方式（单选）、发票信息'
                    },
                    {
                        label: '产品调研问卷',
                        text: '生成产品调研问卷，包含以下字段：调查日期、客户姓名、购买产品、使用频率、产品满意度（1-5分）、功能改进建议（多行文本）、是否会推荐给他人（单选）'
                    },
                    {
                        label: '培训报名表',
                        text: '创建培训报名表，要求包含：姓名、性别、年龄、公司、岗位、联系电话、邮箱、培训课程选择（多选）、报名日期'
                    },
                    {
                        label: '旅行计划表',
                        text: '生成旅行计划表，包含：出发日期、返回日期、出发城市、目的地、交通方式、住宿类型、旅行人数、预算、特别需求'
                    },
                    {
                        label: '采购订单表',
                        text: '生成采购订单表，包含：供应商名称、商品名称、规格型号、数量、单价、总金额、交货日期、收货人、送货地址、付款方式'
                    },
                    {
                        label: '会议安排表',
                        text: '创建会议安排表，包含：会议主题、会议日期、开始时间、结束时间、参会人员、会议地点、主持人、会议议程'
                    },
                    {
                        label: '员工考勤表',
                        text: '生成员工考勤表，要求包含：员工姓名、工号、日期、上班时间、下班时间、出勤状态（正常、迟到、早退、缺勤）、加班时长、请假时长'
                    },
                    {
                        label: '财务报销单',
                        text: '生成财务报销单，包含：报销人姓名、部门、报销日期、报销项目（如交通费、住宿费、餐费）、费用总额、支付方式、发票附件'
                    },
                    {
                        label: '销售报表',
                        text: '生成销售报表，要求包括：销售日期、销售人员、客户名称、销售产品、数量、单价、总金额、支付方式、备注'
                    },
                    {
                        label: '项目计划表',
                        text: '创建项目计划表，包含：项目名称、项目负责人、开始日期、结束日期、项目阶段、任务描述、责任人、进度状态、预计完成日期'
                    },
                    {
                        label: '员工绩效考核表',
                        text: '生成员工绩效考核表，包含：员工姓名、部门、职位、考核周期、绩效评分、达成目标、改进措施、主管意见、员工自评'
                    },
                    {
                        label: '会议签到表',
                        text: '生成会议签到表，包含：会议名称、会议日期、参会人员、签到时间、签到状态（到场、缺席）、备注'
                    },
                    {
                        label: '客户投诉反馈表',
                        text: '创建客户投诉反馈表，包含：投诉日期、客户姓名、联系方式、投诉问题、投诉内容、处理状态、处理结果、处理人员'
                    },
                    {
                        label: '产品库存表',
                        text: '生成产品库存表，包含：产品名称、产品编号、库存数量、入库日期、出库日期、库存状态、供应商信息'
                    },
                    {
                        label: '供应商评价表',
                        text: '创建供应商评价表，要求包含：供应商名称、评价日期、服务质量评分、交货准时性评分、价格满意度、售后服务评分、备注'
                    },
                    {
                        label: '设备维修记录表',
                        text: '创建设备维修记录表，包含：设备名称、设备编号、维修日期、故障描述、维修内容、维修人员、维修费用、维修结果'
                    },
                    {
                        label: '员工离职手续表',
                        text: '生成员工离职手续表，包含：员工姓名、部门、职位、离职日期、离职原因、公司财物归还情况、离职证明领取情况、最终结算'
                    }
                ],
			};
		},
        
    template: `
    <div class="readxlsx">
        <!-- 配置选择对话框 -->
        <el-dialog v-model="showImportDialog" title="选择要导入的项目" width="30%">
            <el-select v-model="selectedConfigIndex" placeholder="选择项目">
            	<el-option v-for="(config, index) in importConfigs" :key="index" :label="config.formname" :value="index"/>
            </el-select>
            <template #footer>
                <el-button @click="showImportDialog = false">取 消</el-button>
                <el-button type="primary" @click="confirmImport">确 定</el-button>
            </template>
        </el-dialog>
  
        <el-form :model="newbgsx" :rules="rules" ref="formRef" label-position="top">
            <el-tabs v-model="activeName">
                <el-tab-pane label="上传创建" name="first">
                    <div style="width:100%;line-height: 1em;"><p style="color:blue;">从下面两种方式中选择一种</p></div>
                    <el-form-item label="查询名称" prop="formname" required v-if="pageState.total > 0">
                        <el-input v-model.trim="newbgsx.formname" placeholder="输入查询名称" clearable />
                    </el-form-item>
                    <el-form-item label="方式1：上传表格" prop="file" style="width:100%" v-if="pageState.total == 0">
                        <el-upload ref="upload" style="width:100%" drag action="#" :auto-upload="false" :limit="1" :on-change="handleFileChange" :before-upload="beforeUpload" accept=".xlsx">
                            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                            <div class="el-upload__text">拖拽文件至此区域或<em>点击上传</em></div>
                            <template #tip>
                                <div style="width:100%;line-height: 1em;">
                                    <h3>说明：</h3>
                                    <p>1. 请上传xlsx格式的表格文件，表格不超过20万行，创建后可再追加导入；</p>
                                    <p>2. 确保至少有两行，第一行为表头，如姓名性别等，且没有合并单元格；第二行以下为数据。</p>
                                    <p>3. 列数最多不超过60，超过的可能数据库无法写入；</p>
                                    <p>4. 上传表格会显示表格内容，可以对数据进行核对；</p>
                                    <p>5. 如果创建表单给用户填报，可直接点击手工创建录入填报字段，无需上传表格。</p>
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="预览数据" v-if="pageState.total > 0" style="width:100%">
        			    <div style="overflow-x: auto;width:100%;margin-top:-5px;">
                        	<div style="margin:10px;">
                        		<span><b style="color:blue;">表格共有{{ pageState.total }}行数据</b></span>
                        		<div style="height: 300px;border-style:solid;border-width:1px;border-color:#babcc1;">
                            		<el-auto-resizer>
                                        <template #default="{ height, width }">
                                    		<el-table-v2 :columns="getcolumns(tempjson)" :data="gettempdata(tempjson)" :width="width" :height="height" fixed></el-table-v2>
                                    	</template>
                                    </el-auto-resizer>
                                </div>
                        	</div>
        			    </div>
                        
                        <div v-if="pageState.percent > 0" class="progress-container">
                            <div class="progress-info">
                                <span>导入进度：{{ pageState.percent }}%</span>
                                <span>{{ pageState.percent === 100 ? '导入完成' : '正在导入...' }}</span>
                            </div>
                            <div class="progress-bar">
                                <div class="progress-inner" :style="{ width: pageState.percent + '%' }"></div>
                            </div>
                        </div>
                    </el-form-item>
                    <el-divider />
                    <el-form-item label="方式2：从备份配置中导入" v-if="pageState.total === 0">
                        <el-upload action="#" :show-file-list="false" :before-upload="(file) => { handleJsonImport({ raw: file }); return false }" accept=".json">
                            <el-button type="warning" size="small">
                                <el-icon><Upload /></el-icon>导入JSON配置
                            </el-button>
                            <template #tip>
                                <div class="el-upload__tip">仅支持之前导出的配置文件格式</div>
                            </template>
                        </el-upload>
                    </el-form-item>
                </el-tab-pane>
                
                <el-tab-pane label="手工创建" name="two">
                    <el-form-item label="查询名称" prop="formname" required v-if="pageState.total == 0 && fieldOrder.length">
                        <el-input v-model.trim="newbgsx.formname" placeholder="输入查询名称" clearable />
                    </el-form-item>
                    <el-form-item label="填报内容" required>
                        <div class="sortable-container" style="width:100%;">
                            <el-row :gutter="20" v-for="key in fieldOrder" :key="key" style="width:100%;margin:5px;">
                                <el-col :span="19">
                                    <el-input v-model="newbgsx.fields[key].name" placeholder="输入列名">
                                        <template #prefix>{{ key }}：</template>
                                        <template #append>
                                            <el-icon @click="moveItemUp(key)"><Top /></el-icon> &nbsp;&nbsp;
                                            <el-icon @click="moveItemDown(key)"><Bottom /></el-icon>
                                        </template>
                                    </el-input>
                                </el-col>
                                <el-col :span="5">
        							<el-button size="small" type="danger" @click="removeField(key)">删除</el-button>
        						</el-col>
                            </el-row>
                        </div>
                        <el-button type="success" size="small" @click="addField">添加</el-button>
                    </el-form-item>
                    <h4 class="text-center" style="color: #0055ff">字段类型(先选数据列，再选类型)</h4>
                    
                    <el-row :gutter="20">
                    	<el-col :span="16">
                    		<el-form-item label="数据列" prop="at">
                    			<el-select v-model="at" placeholder="选择数据列">
                    				<el-option v-for="item in zdoption" :key="item.value" :label="item.label"
                    					:value="item.value" />
                    			</el-select>
                    		</el-form-item>
                    	</el-col>
                    	<el-col :span="8" v-if="at">
                    		<el-form-item label="类型" prop="type">
                    			<el-select v-model="newbgsx.fields[at].type" placeholder="选择类型" @change="lxchang">
                    				<el-option v-for="item in lx" :key="item.value" :label="item.label"
                    					:value="item.value" />
                    			</el-select>
                    		</el-form-item>
                    	</el-col>
                    </el-row>
                    
                    <template v-if="at">
                    	<el-row :gutter="20">
                    		<el-col :span="8">
                    			<el-form-item label="名称" prop="name">
                    				<el-input v-model.trim="newbgsx.fields[at].name" placeholder="字段名称" />
                    			</el-form-item>
                    		</el-col>
                    		<el-col :span="8">
                    			<el-form-item label="提示文字" prop="placeholder">
                    				<el-input v-model.trim="newbgsx.fields[at].placeholder" placeholder="提示文字" />
                    			</el-form-item>
                    		</el-col>
                    		
                    		<el-col :span="8" v-if="!['image','multiimage'].includes(newbgsx.fields[at].type)">
                    			<el-form-item label="默认值" prop="default">
                    				<el-input v-model.trim="newbgsx.fields[at].default" placeholder="设置默认值" />
                    			</el-form-item>
                    		</el-col>
                    		<el-col :span="8">
                    			<el-form-item label="必填" prop="required">
                    				<el-switch v-model="newbgsx.fields[at].required" />
                    			</el-form-item>
                    		</el-col>
                    	
                    		<el-col :span="8" v-if="['image','multiimage'].includes(newbgsx.fields[at].type)">
                    			<el-form-item label="图片压缩" prop="options">
                    				<el-input v-model="newbgsx.fields[at].options" placeholder="宽高用/分割，如300/200" />
                    			</el-form-item>
                    		</el-col>
                    		<el-col :span="8" v-if="newbgsx.fields[at].type === 'multiimage'">
                    			<el-form-item prop="max" label="数量">
                    				<el-input-number v-model="newbgsx.fields[at].max" :min="1" />
                    			</el-form-item>
                    		</el-col>
                    		<el-col :span="8" v-if="['select','muselect', 'radio', 'checkbox'].includes(newbgsx.fields[at].type)">
                    			<el-form-item label="选项" prop="options">
                    				<el-input type="textarea" v-model="newbgsx.fields[at].options" placeholder="用/分割选项" />
                    			</el-form-item>
                    		</el-col>
                    	</el-row>
                    	
                        <el-form-item label="可修改用户，不选则不限" prop="edituser">
    						<el-select multiple v-model="newbgsx.fields[at].edituser" placeholder="选择允许修改的用户" style="width: 100%">
    							<el-option v-for="item in tbyoptions" :key="item.value" :label="item.label" :value="item.value" />
    						</el-select>
    					</el-form-item>
                    
                    	<template v-if="newbgsx.fields[at].type === 'idcard'">
                    		<h4 class="text-center" style="color: #c76395">拍摄身份证后识别内容，并自动填写到对应字段</h4>
                    		<el-form-item label="身份证识别字段" prop="sfzoptions">
                    			<el-row :gutter="10" style="width:100%">
                    				<el-col :span="8">
                    					<el-select v-model="newbgsx.fields[at].sfzoptions.name" placeholder="姓名">
                    						<el-option v-for="item in zdoption" :key="item.value" :label="item.label"
                    							:value="item.value" />
                    					</el-select>
                    				</el-col>
                    				
                    				<el-col :span="8">
                    					<el-select v-model="newbgsx.fields[at].sfzoptions.sex" placeholder="性别">
                    						<el-option v-for="item in zdoption" :key="item.value" :label="item.label"
                    							:value="item.value" />
                    					</el-select>
                    				</el-col>
                    				
                    				<el-col :span="8">
                    					<el-select v-model="newbgsx.fields[at].sfzoptions.mz" placeholder="民族">
                    						<el-option v-for="item in zdoption" :key="item.value" :label="item.label"
                    							:value="item.value" />
                    					</el-select>
                    				</el-col>
                    				
                    				<el-col :span="8">
                    					<el-select v-model="newbgsx.fields[at].sfzoptions.day" placeholder="出生日期">
                    						<el-option v-for="item in zdoption" :key="item.value" :label="item.label"
                    							:value="item.value" />
                    					</el-select>
                    				</el-col>
                    				
                    				<el-col :span="8">
                    					<el-select v-model="newbgsx.fields[at].sfzoptions.ade" placeholder="住址">
                    						<el-option v-for="item in zdoption" :key="item.value" :label="item.label"
                    							:value="item.value" />
                    					</el-select>
                    				</el-col>
                    				
                    				<el-col :span="8">
                    					<el-select v-model="newbgsx.fields[at].sfzoptions.old" placeholder="周岁">
                    						<el-option v-for="item in zdoption" :key="item.value" :label="item.label"
                    							:value="item.value" />
                    					</el-select>
                    				</el-col>
                    			</el-row>
                    		</el-form-item>
                    	</template>
                    </template>
                </el-tab-pane>
                
                <el-tab-pane label="AI创建" name="third">
        			<el-form-item label="表单需求描述" prop="aiPrompt">
        				<el-input v-model="aiPrompt" type="textarea" :rows="4" placeholder="请描述您需要的表单，例如：创建一个员工信息登记表，包含姓名、身份证号、入职日期等字段" />
                    </el-form-item>
                    <div class="example-prompts">
                        <div class="prompt-title">常用模板：</div>
                        <el-tag v-for="(prompt, index) in examplePrompts" :key="index" class="prompt-tag" effect="plain" @click="aiPrompt = prompt.text">
                            {{ prompt.label }}
                        </el-tag>
                    </div>
                    <el-button type="primary" :loading="isGenerating" @click="generateAIForm">
                    	{{ isGenerating ? '生成中...' : '智能生成表单' }}
                    </el-button>
                    <div v-if="fieldOrder.length > 0" class="generated-preview">
                    	<h4>生成的字段结构：</h4>
                    	<el-tag v-for="key in fieldOrder" :key="key" class="field-tag">
                    		{{ newbgsx.fields[key].name }} ({{ newbgsx.fields[key].type }})
                    	</el-tag>
                    </div>
        		</el-tab-pane>
            </el-tabs>
            <el-row justify="center">
                <el-col :span="8" style="text-align: center;margin: 20px;">
                    <el-button type="primary" v-if="newbgsx.formname && (pageState.total > 0 || fieldOrder.length)" size="large" style="margin-right:20px" @click="handleCreate()">提交</el-button>
                    <el-button @click="closeDialog()" size="large">取消</el-button>
                </el-col>
    		</el-row>
        </el-form>
    </div>
    `
}